<template>
  <div class="form-container">
    <div v-if="formModel.cite" class="tips">
      <div>1. 该题目已被引用，编辑内容会自动同步&nbsp;<el-button link type="primary" @click="handleCite()">查看引用内容 </el-button></div>
      <div>2. 编辑正确选项会对引用该题的考试数据统计准确率造成影响，请知晓</div>
    </div>
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="80px" style="max-width: 980px" @submit.prevent>
      <div class="form-main">
        <div class="form-main-title">基础信息</div>
        <div class="form-main-content">
          <el-form-item label="目录" prop="categoryId">
            <cascader-classify v-model="formModel.categoryId" :category-type="3" />
          </el-form-item>
          <el-form-item class="form-group" label="题型" prop="questionType">
            <enum-radio v-model="formModel.questionType" :enum-name="'QuestionType'" :disabled="formModel.id > 0" />
          </el-form-item>
          <el-form-item class="form-group" label="难度" prop="difficultyLevel">
            <enum-radio v-model="formModel.difficultyLevel" :enum-name="'DifficultyLevel'" />
          </el-form-item>
          <el-form-item label="题目" prop="questionTitle">
            <editor-question v-model="formModel.questionTitle" />
          </el-form-item>

          <template v-if="formModel.questionType === 1 || formModel.questionType === 2">
            <!-- 单选题、多选题 -->
            <el-form-item v-for="(item, index) in formModel.options" :key="index" :label="'选项' + changeNumToEn(index)">
              <editor-question v-model="formModel.options[index].optionContent" />
              <el-button type="danger" :icon="Delete" style="margin-left: 755px" @click="handleDelOption(index)" />
            </el-form-item>
            <el-button type="primary" style="margin-left: 800px" @click="handleAddOption">增加选项</el-button>
          </template>
        </div>
      </div>
      <div class="form-main">
        <div class="form-main-title">答案解析</div>
        <div class="form-main-content">
          <el-form-item label="答案" prop="questionAnswer">
            <template v-if="formModel.questionType === 1">
              <!-- 单选题 -->
              <el-radio-group v-model="formModel.questionAnswer">
                <el-radio v-for="(item, index) in formModel.options" :key="index" :value="item.optionContent">
                  {{ '选项' + changeNumToEn(index) }}
                </el-radio>
              </el-radio-group>
            </template>
            <template v-if="formModel.questionType === 2">
              <!-- 多选题 -->
              <el-checkbox-group v-model="formModel.questionAnswer2" @change="handleCheckboxChange">
                <el-checkbox v-for="(item, index) in formModel.options" :key="index" :value="item.optionContent">
                  {{ '选项' + changeNumToEn(index) }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
            <template v-if="formModel.questionType === 3">
              <!-- 判断题 -->
              <el-radio-group v-model="formModel.questionAnswer">
                <el-radio value="对">对</el-radio>
                <el-radio value="错">错</el-radio>
              </el-radio-group>
            </template>
            <template v-if="formModel.questionType === 4">
              <!-- 填空题 -->
              <div v-for="(item, index) in formModel.questionAnswer4" :key="index" style="width: 100%; margin-bottom: 10px">
                <el-input v-model="formModel.questionAnswer4[index]" :placeholder="'请输入空' + (index + 1) + '答案'">
                  <template #append>
                    <el-button :icon="Delete" @click="handleDelAnswer(index)" />
                  </template>
                </el-input>
              </div>
              <el-button type="primary" @click="handleAddAnswer">增加答案</el-button>
            </template>
            <template v-if="formModel.questionType === 5">
              <!-- 简答题 -->
              <editor-question v-model="formModel.questionAnswer" />
            </template>
            <template v-if="formModel.questionType === 6">
              <!-- 材料题 -->
              该题型暂不支持
            </template>
          </el-form-item>
          <el-form-item label="解析" prop="questionAnalysis">
            <editor-question v-model="formModel.questionAnalysis" />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div class="form-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="onSubmit()">确定</el-button>
    </div>
  </div>
</template>
<script setup>
  import { ElMessage } from 'element-plus'
  import { onMounted, reactive, ref } from 'vue'
  import { questionApi } from '@/api/question.js'
  import EditorQuestion from '@/components/Editor/Question.vue'
  import CascaderClassify from '@/components/Cascader/Classify/index.vue'
  import EnumRadio from '@/components/Enum/Radio/index.vue'
  import { useRouter } from 'vue-router'
  import { useRoute } from 'vue-router/dist/vue-router'
  import { Delete } from '@element-plus/icons-vue'
  import { changeNumToEn } from '@/utils/base.js'

  const router = useRouter()

  // 增加选项
  const handleAddOption = () => {
    if (formModel.options.length > 10) {
      ElMessage.warning('选项数不能多于10个')
      return
    }
    formModel.options.push({ optionContent: '' })
  }
  // 删除选项
  const handleDelOption = (index) => {
    if (formModel.options.length < 2) {
      ElMessage.warning('选项数不能少于1个')
      return
    }
    formModel.options.splice(index, 1)
  }

  // 增加答案
  const handleAddAnswer = () => {
    formModel.questionAnswer4.push('')
  }
  // 删除答案
  const handleDelAnswer = (index) => {
    if (formModel.questionAnswer4.length < 2) {
      ElMessage.warning('答案数不能少于1个')
      return
    }
    formModel.questionAnswer4.splice(index, 1)
  }

  // 校验规则
  const formRef = ref()
  const rules = {
    categoryId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    courseName: [{ required: true, message: '不能为空', trigger: 'blur' }],
    lecturerId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    courseLogo: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }

  // 多选题答案处理
  const handleCheckboxChange = (value) => {
    formModel.questionAnswer2 = []
    formModel.options.forEach((option) => {
      value.forEach((item) => {
        if (option.optionContent === item) {
          formModel.questionAnswer2.push(option.optionContent)
        }
      })
    })
  }

  //查看引用
  // 删除
  const citeRef = reactive({})
  const handleCite = async () => {
    citeRef.visible = true
    citeRef.questionId = formModel.id
    citeRef.title = formModel.questionTitle
  }

  // 表单
  const loading = ref(false) // 加载进度状态
  const emit = defineEmits(['refresh'])
  const formDefault = {
    id: undefined,
    categoryId: undefined,
    difficultyLevel: 1,
    questionType: 1,
    options: [{ optionContent: '' }, { optionContent: '' }, { optionContent: '' }, { optionContent: '' }],
    questionAnswer: undefined,
    questionAnswer4: [''],
    questionAnalysis: ''
  }
  const formModel = reactive({ ...formDefault })
  const onSubmit = async () => {
    // 校验
    const valid = await formRef.value.validate()
    if (!valid) return

    if (formModel.questionType === 2) {
      // 多选题
      formModel.questionAnswer = []
      formModel.questionAnswer = formModel.questionAnswer2.join('|')
    }
    if (formModel.questionType === 3) {
      // 判断题
      formModel.options = [{ optionContent: '对' }, { optionContent: '错' }]
    }
    if (formModel.questionType === 4) {
      // 填空题
      formModel.questionAnswer = formModel.questionAnswer4.join('|')
      delete formModel.options
    }
    if (formModel.questionType === 5) {
      // 简答题
      delete formModel.options
    }

    // 多余的参数，不传到后端
    delete formModel.questionAnswer2
    delete formModel.questionAnswer4

    if (loading.value === true) {
      ElMessage.warning('正在处理···')
      return
    }
    loading.value = true
    try {
      if (formModel.id) {
        await questionApi.questionEdit(formModel)
        ElMessage.success('修改成功')
      } else {
        await questionApi.questionSave(formModel)
        ElMessage.success('添加成功')
      }
      handleClose()
      emit('refresh')
    } finally {
      loading.value = false
    }
  }
  // 初始化
  const route = useRoute()
  onMounted(async () => {
    if (route.query.questionId) {
      const res = await questionApi.questionView({ id: route.query.questionId })
      Object.assign(formModel, res)
      if (route.query.isCopy) {
        formModel.id = undefined
        formModel.cite = undefined
      }

      if (formModel.questionType === 2) {
        // 多选题答案处理
        formModel.questionAnswer2 = formModel.questionAnswer.split('|')
      }

      if (formModel.questionType === 4) {
        // 填空题答案处理
        formModel.questionAnswer4 = formModel.questionAnswer.split('|')
      }
    } else {
      Object.assign(formModel, formDefault)
    }
  })
  const handleClose = () => {
    router.go(-1)
  }
</script>
